﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;

using JigsawService.Utility;

namespace JigsawService.Parsers
{
    public class APIMessage
    {
        string _location = "";
        string _serverip = "";
        string _clientip = "";

        string _requesttime = "0";
        string _requestguid = "";
        string _sessionguid = "";

        string _username = "";
        string _password = "";
        string _encpassword = "";

        string _apiname = "";
        string _apistring = "";
        string _versionparamstring = "";

        string _userid = "0";
        string _userauthorization = "";

        string _processstate = "";
        string _statemessage = "";
        string _starttime = "0";
        string _endtime = "0";

        string _responsecode = "";
        string _responsetype = "";
        string _methodresult = "";

        string _apilist = "";
        string _grouplist = "";

        Dictionary<string, string> _versionparams;

        List<string> _apiaccess;
        List<string> _groupaccess;
        
        /// <summary>
        /// 
        /// </summary>
        public APIMessage()
        {
            _versionparams = new Dictionary<string, string>();
            _apiaccess = new List<string>();
            _groupaccess = new List<string>();
        }

        public string RequestGUID
        {
            set { _requestguid = value; }
            get { return _requestguid; }
        }

        public string RequestTime
        {
            set { _requesttime = value; }
            get { return _requesttime; }
        }

        public string SessionGUID
        {
            set { _sessionguid = value; }
            get { return _sessionguid; }
        }

        public string Location
        {
            set { _location = value; }
            get { return _location; }
        }

        public string ServerIP
        {
            set { _serverip = value; }
            get { return _serverip; }
        }

        public string ClientIP
        {
            set { _clientip = value; }
            get { return _clientip; }
        }

        public string UserName
        {
            set { _username = value; }
            get { return _username; }
        }

        public string Password
        {
            set 
            { 
                _password = value;
                SetEncryptedPassword();
            }
            get { return _password; }
        }

        public string EncryptedPassword
        {
            get { return _encpassword; }
        }

        public string APIName
        {
            set { _apiname = value; }
            get { return _apiname; }
        }

        public string APIString
        {
            set { _apistring = value; }
            get { return _apistring; }
        }

        public string VersionParamString
        {
            set 
            { 
                _versionparamstring = value;
                ParseMethodParams();
            }
            get { return _versionparamstring; }
        }

        public Dictionary<string, string> VersionParams
        {
            get { return _versionparams; }
        }

        public string UserID
        {
            set { _userid = value; }
            get { return _userid; }
        }

        public string UserAuthorization
        {
            set 
            {
                _userauthorization = value;
                if (_userauthorization.Length > 0) ParseUserAuthorization();
            }
            get { return _userauthorization; }
        }

        public string ProcessState
        {
            set { _processstate = value; }
            get { return _processstate; }
        }

        public string StateMessage
        {
            set { _statemessage = value; }
            get { return _statemessage; }
        }

        public string StartTime
        {
            set { _starttime = value; }
            get { return _starttime; }
        }

        public string EndTime
        {
            set { _endtime = value; }
            get { return _endtime; }
        }

        public string ResponseCode
        {
            set { _responsecode = value; }
            get { return _responsecode; }
        }

        public string ResponseType
        {
            set { _responsetype = value; }
            get { return _responsetype; }
        }

        public string MethodResult
        {
            set { _methodresult = value; }
            get { return _methodresult; }
        }

        public string APIListToString
        {
            get { return _apilist; }
        }

        public string GroupListToString
        {
            get { return _grouplist; }
        }


        public void SetEncryptedPassword()
        {
            if (_username != "" && _password != "")
            {
                EncryptionUtility eutil = new EncryptionUtility();
                _encpassword = eutil.PasswordHash(_username, _password);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public string ValidateMethodParam(string paramName)
        {
            string paramvalue = "";

            if (_versionparams != null || _versionparams.Count > 0)
            {
                _versionparams.TryGetValue(paramName, out paramvalue);
                if (paramvalue == null) paramvalue = "";
            }

            return paramvalue;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="versionparamstr"></param>
        /// <returns></returns>
        private void ParseMethodParams()
        {
            if (_versionparamstring != null && _versionparamstring.Length > 0)
            {
                
                string[] paramlist = _versionparamstring.Split(new char[] { '|' });
                if (paramlist.Length > 0)
                {
                    foreach (string param in paramlist)
                    {
                        string[] nvp = param.Split(new char[] { '^' });

                        if (nvp.Length > 0)
                        {
                            string pname = nvp[0];
                            string pvalue = nvp[1];

                            // avoid adding duplicate params
                            if (!_versionparams.ContainsKey(pname))
                            {
                                _versionparams.Add(pname, pvalue);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="methodName"></param>
        /// <returns></returns>
        public bool ValidateMethodAccess(string methodName)
        {
            bool hasAccess = false;

            if (_apiaccess != null && _apiaccess.Count > 0)
            {
                if (_apiaccess.Contains(methodName)) hasAccess = true;
            }
            else
            {
                throw new Exception("APIMessage ValidateMethodAccess: Unable to determine if method access is authorized.");
            }

            return hasAccess;
        }

        /// <summary>
        /// The userauthorization value is a comma delimited list of method names,
        /// a vertical bar delimiter, and a comma delimited list of group ID values
        /// 
        /// This method a) sets the appropriate property values with the delimited strings,
        /// and b) parses the comma delimited strings into generic List<string> collections
        /// </summary>
        private void ParseUserAuthorization()
        {
            if (_userauthorization != null && _userauthorization.Length > 0)
            {
                // split the method access from the group access
                string[] autharray = _userauthorization.Split(new char[] { '|' });

                if (autharray.Length == 2)
                {
                    _apilist = autharray[0];
                    _grouplist = autharray[1];

                    string[] methodArray = _apilist.Split(new char[] { ',' });
                    _apiaccess = new List<string>(methodArray);

                    string[] groupArray = _grouplist.Split(new char[] { ',' });
                    _groupaccess = new List<string>(groupArray);
                }
                else
                {
                    throw new Exception("APIMessage ParseUserAuthorization: Error parsing the userauthorization string.");
                }
            }
            else
            {
                throw new Exception("APIMessage ParseUserAuthorization: Missing the userauthorization string.");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetNewID()
        {
            return System.Guid.NewGuid().ToString().Replace("-", "");
        }
    }
}